﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using App.Metrics;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using StudyAppMetircs.Models;

namespace StudyAppMetircs.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IMetrics _metrics;

        public HomeController(ILogger<HomeController> logger, IMetrics metrics)
        {
            _logger = logger;
            _metrics = metrics;
        }

        public IActionResult Index()
        {
            Response.Headers.Add("Access-Control-Allow-Origin", "*");
            Response.Headers.Add("Authorization", "Bearer eyJrIjoiNEt6VEVJcTlTa2lhalg1RmZLZTR1MTF3dGoxTnlCbXAiLCJuIjoi5oiR55qE56ys5LiA5LiqQVBJ6ZSuIiwiaWQiOjF9");
            return View();
        }

        public IActionResult Privacy()
        {
            _logger.LogInformation("测试日志输出");
            _metrics.Measure.Counter.Increment(MetricsRegistry.SampleCounter);
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }

        public async Task GrafanaAsync()
        {

            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer eyJrIjoiNEt6VEVJcTlTa2lhalg1RmZLZTR1MTF3dGoxTnlCbXAiLCJuIjoi5oiR55qE56ys5LiA5LiqQVBJ6ZSuIiwiaWQiOjF9");

            var response = await client.GetAsync("http://localhost:3000/d/8ELZ1an7z/app-metrics-web-monitoring-influxdb-myseconddatabase?orgId=1&refresh=5s&from=1629787837807&to=1629788137807");
           var st = await response.Content.ReadAsStreamAsync();
            var str = await response.Content.ReadAsStringAsync();
            str = str.Replace("<base href=\"/\" />", "<base href=\"http://localhost:3000\" />");
            var bytes = Encoding.UTF8.GetBytes(str);

            await Response.Body.WriteAsync(bytes, 0, bytes.Length);
            //await st.CopyToAsync(Response.Body);
        }
    }
}
